package com.hns.can.master.service;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.tool.pub.UtilConfig;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.entity.BaseCarDrvRelEntity;
import com.hns.can.master.entity.BaseDrvInfoEntity;
import com.hns.can.master.enumrate.DriverSt;
import com.hns.can.master.vo.DrvPostDataVo;
import com.hns.frame.dao.SqlMapDao;
import com.hns.frame.enumrate.EnabledSt;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 驾驶员信息维护业务类
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Service
public class BaseDrvInfoService extends CommonService {

    private static final Logger logger = LoggerFactory.getLogger(BaseDrvInfoService.class);
	/**
	 * 代码描述
	 */
    @Autowired
    private FillCodeDscValue codeDscValue;
    @Autowired
    private SqlMapDao sqlMaoDao;
    
    
	/**
	 * 根据BaseDrvInfoEntity获取驾驶员列表
	 * @param entity
	 * @return
	 * @author:lan
	 * @email:763836737@qq.com
	 */
    @SuppressWarnings("unchecked")
    public List<BaseDrvInfoEntity> getBaseDrvInfoList(BaseDrvInfoEntity entity) {
	    List<BaseDrvInfoEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseDrvInfo.getBaseDrvInfoList", entity), BaseDrvInfoEntity.class);
	    return list;
    }
    
    /**
     * 添加一个驾驶员
     * @param entity
     * @param user
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_DRV_INFO, key="#user.getCorpId()")
    public void addDriverInfo(BaseDrvInfoEntity entity, SysUserEntity user) {
        // 补充实体的其他信息
        entity.setDrvId(UtilString.getUUID());
        entity.setEnabledSt(EnabledSt.ENABLE.getFlag());  // 启用状态
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        // 后台校验
        // -- 司机姓名 drvName
//        this.check("baseDrvInfo.checkDrvName", entity, "您输入的司机姓名已经存在，可能存在同名的情况，请在名字上加一些注释。");
        // -- 身份证号 idcardNo
        if(PubUtil.isNotEmpty(entity.getIdcardNo())){
            this.check("baseDrvInfo.checkIdcardNo", entity, "您输入的身份证号已经存在！");
        }
        // -- 驾驶证号 driLicNo
        if(PubUtil.isNotEmpty(entity.getDriLicNo())){
            this.check("baseDrvInfo.checkDriLicNo", entity, "您输入的驾驶证号已经存在！");
        }
        // -- 员工工号 workEmpeEmpno
        if(PubUtil.isNotEmpty(entity.getWorkEmpeEmpno())){
            this.check("baseDrvInfo.checkWorkEmpeEmpno", entity, "您输入的员工工号已经存在！");
        }
        // -- 考勤卡卡号 timecardCardno
        if(PubUtil.isNotEmpty(entity.getTimecardCardno())){
            this.check("baseDrvInfo.checkTimecardCardno", entity, "您输入的考勤卡卡号已经存在！");
        }
        // -- 考勤卡卡面号 timecardCardnum
        if(PubUtil.isNotEmpty(entity.getTimecardCardnum())){
            this.check("baseDrvInfo.checkTimecardCardnum", entity, "您输入的考勤卡卡面号已经存在！");
        }
        commonEntityDao.save(entity);
    }
    
    /**
     * 得到驾驶员page对象
     * @param dataVo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Pagination searchDriverInfoPage(DrvPostDataVo dataVo) throws Exception {
        Pagination page = this.myBatisPage("baseDrvInfo.getDriverInfoCnt","baseDrvInfo.getDriverInfoList", dataVo,BaseDrvInfoEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("organId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[] {GlobalConst.CACHE_KEY_BASE_ORGAN},vo);
        return page;
    }
    
    /**
     * 得到驾驶员信息list对象
     * @param dataVo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings({"unchecked" })
    @Transactional
    public List<BaseEntity> getDriverInfoList(DrvPostDataVo dataVo) throws Exception {
    	List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseDrvInfo.getDriverInfoList", dataVo), BaseDrvInfoEntity.class);
        Map<String,String> mapTmp = new HashMap<String,String>();
        mapTmp.put("gender", "SEX00000");
        mapTmp.put("driLicType", "DLT00000");
        mapTmp.put("st", "EMS00000");
        codeDscValue.fillCodeDscValue(list, mapTmp);
        Map<String,String> map = new HashMap<String,String>();
        map.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("organId", map);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_BASE_ORGAN},vo);
        return list;
    }
    
   /**
    * 根据驾驶员id求驾驶员信息
    * @param drvId
    * @return
    * @throws Exception
    * @author:lan
    * @email:763836737@qq.com
    */
    @Transactional
    public BaseDrvInfoEntity  getDriverInfoByDrvId(String drvId) throws Exception {
        BaseDrvInfoEntity entity = commonEntityDao.find(drvId, BaseDrvInfoEntity.class);
        List<BaseEntity> list = new ArrayList<BaseEntity>();
        list.add(entity);
        Map<String,String> map = new HashMap<String,String>();
        map.put("corpName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("corpId", map);
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo2 = new FillParamsVo("organId", map2);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_SYS_CORP, GlobalConst.CACHE_KEY_BASE_ORGAN},vo,vo2);
        return entity;
    }
    
    /**
     * 更新一个驾驶员的信息
     * @param user
     * @param entity
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_DRV_INFO, key="#user.getCorpId()")
    public void uptDriverInfo(SysUserEntity user, BaseDrvInfoEntity entity){
        BaseDrvInfoEntity tmpEntity = commonEntityDao.find(entity.getDrvId(), BaseDrvInfoEntity.class);
        entity.setEnabledSt(tmpEntity.getEnabledSt());  // 启用状态
        entity.setCrtTime(tmpEntity.getCrtTime());
        entity.setCrtUser(tmpEntity.getCrtUser());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        // 后台校验
        // -- 司机姓名 drvName
        if(PubUtil.isNotEmpty(entity.getDrvName())){
            this.check("baseDrvInfo.checkDrvName",entity,"您输入的司机姓名已经存在，可能存在同名的情况，请在名字上加一些注释。");
        }
        // -- 身份证号 idcardNo
        if(PubUtil.isNotEmpty(entity.getIdcardNo())){
            this.check("baseDrvInfo.checkIdcardNo",entity,"您输入的身份证号已经存在！");
        }
        // -- 驾驶证号 driLicNo
        if(PubUtil.isNotEmpty(entity.getDriLicNo())){
            this.check("baseDrvInfo.checkDriLicNo",entity,"您输入的驾驶证号已经存在！");
        }
        // -- 员工工号 workEmpeEmpno
        if(PubUtil.isNotEmpty(entity.getWorkEmpeEmpno())){
            this.check("baseDrvInfo.checkWorkEmpeEmpno",entity,"您输入的员工工号已经存在！");
        }
        // -- 考勤卡卡号 timecardCardno
        if(PubUtil.isNotEmpty(entity.getTimecardCardno())){
            this.check("baseDrvInfo.checkTimecardCardno",entity,"您输入的考勤卡卡号已经存在！");
        }
        // -- 考勤卡卡面号 timecardCardnum
        if(PubUtil.isNotEmpty(entity.getTimecardCardnum())){
            this.check("baseDrvInfo.checkTimecardCardnum",entity,"您输入的考勤卡卡面号已经存在！");
        }
        // 更新的关联操作
        // 在职改变成离职，对应要考虑删除驾驶员车辆分配信息表
        if(DriverSt.ON_JOB.getFlag().equals(tmpEntity.getSt()) && DriverSt.LEAVE_JOB.getFlag().equals(entity.getSt())){
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("drvId", entity.getDrvId());
            List<BaseCarDrvRelEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseCarDrvRelEntity.class, params);
            if(PubUtil.isNotEmpty(list)){
                for(BaseCarDrvRelEntity carDrvRel : list){
                    commonEntityDao.delete(carDrvRel);
                }
            }
        }
        commonEntityDao.update(entity);
    }
    
    /**
     * 删除一个驾驶员
     * @param user
     * @param drvIds
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_DRV_INFO, key="#user.getCorpId()")
    public void delDriverInfo(SysUserEntity user, String[] drvIds){
        for (String drvId : drvIds) {
            BaseDrvInfoEntity entity = commonEntityDao.find(drvId, BaseDrvInfoEntity.class);
            entity.setEnabledSt(EnabledSt.DISABLE.getFlag());
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(user.getAcctName());
            commonEntityDao.update(entity);
        }
    }
    
    /**
     * 校验司机所属车辆
     * @param drvId
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public boolean validateCarDrvRel(String drvId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("drvId", drvId);
        List<BaseCarDrvRelEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseCarDrvRelEntity.class, params);
        if(list.size() > 0){
            return true;
        }
        return false;
    }
    
    /**
     * 将数据存到数据库中
     * @param list
     * @param user
     * @param orgId
     * @return
     * @throws Exception 
     */
    @Transactional(rollbackFor=Exception.class)
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_DRV_INFO, key="#user.getCorpId()")
    public String saveDriverInfoToDB(List<BaseDrvInfoEntity> list,SysUserEntity user,String orgId) throws Exception{
    	int count = 3;
        successCount = 0;
        String msgs = "";
        String allMsg= "";
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	//通过机构ID找到企业ID
    	Map<String,String> mapId = new HashMap<String,String>();
    	mapId.put("orgId", orgId);
    	Map<String,String> map = (Map<String, String>) sqlMaoDao.selectOne("baseDrvInfo.searchCorp",mapId);
    	String corpId = map.get("CORP_ID");
    	for(BaseDrvInfoEntity entity:list){
            count++;
    		if(PubUtil.isEmpty(entity.getDrvName())){
                msgs = "";
                msgs = "第"+count+"的驾驶员姓名不能为空。<br/> ";
                allMsg = allMsg + msgs;
                continue;
    		}
    		if(PubUtil.isEmpty(entity.getGender())){
                msgs = "";
                msgs = "第"+count+"的性别不能为空。<br/> ";
                allMsg = allMsg + msgs;
                continue;
            }
            successCount++;
    		if(PubUtil.isEmpty(entity.getTimecardCardno())){
    			entity.setTimecardCardno(entity.getWorkEmpeEmpno());
    		}
    		//性别
    		String gender = entity.getGender();
    		entity.setGender(gender);
    		//文化程度
    		String cultuDgr = entity.getCultuDgr();
    		entity.setCultuDgr(cultuDgr);
    		//驾驶证类型
    		String driLicType = entity.getDriLicType();
    		entity.setDriLicType(driLicType);
    		//启停状态
    		entity.setEnabledSt("1");
    		//企业
    		entity.setCorpId(corpId);
    		//机构
    		entity.setOrganId(orgId);
    		//判断驾驶员是否存在
    		mapId.put("timecardCardno", entity.getTimecardCardno());
    		Map<String, String> map1= (Map<String, String>) sqlMaoDao.selectOne("baseDrvInfo.checkDriver",mapId);
    		if(PubUtil.isEmpty(map1)){
    			//主键
        		entity.setDrvId(UtilString.getUUID());
    			//创建时间
        		entity.setCrtTime(new Date());
        		//创建人
        		entity.setCrtUser(user.getAcctName());
        		this.commonEntityDao.save(entity);
    		}else{
    			//创建时间
    			String crtTime = map1.get("CRT_TIME");
    			if(PubUtil.isEmpty(crtTime)){
                    crtTime = sdf.format(new Date()).toString();
                }
        		entity.setCrtTime(sdf.parse(crtTime));
        		//创建人
        		entity.setCrtUser(map1.get("CRT_USER"));
    			//更新时间
        		entity.setUpdateTime(new Date());
        		//更新人
        		entity.setUpdateUser(user.getAcctName());
    			entity.setDrvId(map1.get("DRV_ID"));
    			this.commonEntityDao.update(entity);
    		}
      	}
    	return allMsg;
    }

    /**
     *
     * @param driverHead
     * @param uploadPath
     * @param drvId
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public void returnDrvHeadPath(@RequestParam MultipartFile[] driverHead, String uploadPath, String drvId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
        //这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
//        String realPath = request.getSession().getServletContext().getRealPath("/") + uploadPath;
        //自定义图片保存路径
        String realPath = UtilConfig.getString("upload_file_base_path") + uploadPath;
        //上传文件的全名(上传图片的全名)
        String originalFilename = null;
        //保存的文件名
        String saveFileName = null;
        //设置返回的数据格式
        response.setContentType("text:plain;charset=UTF-8");
        //设置返回给前台内容的PrintWriter对象
        PrintWriter out = response.getWriter();
        //新建驾驶员信息时,drvId是空的
        if(PubUtil.isEmpty(drvId)){
            drvId = UtilString.getUUID();
        }
        //上传文件的原名(即上传前的文件名字)
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
        //上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
        for(MultipartFile myFile:driverHead){
            if(myFile.isEmpty()){
                throw new BusinessException(MsgType.WARN.getFlag(), "请选择文件后上传");
            }
            originalFilename = new String(myFile.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");
            String suffix = originalFilename.substring(originalFilename.indexOf(".")+1,originalFilename.length());
            if("jpg".equals(suffix) || "png".equals(suffix)){
                saveFileName = new String(drvId.getBytes("ISO-8859-1"),"UTF-8")+"."+suffix;
            }else{
                throw new BusinessException(MsgType.WARN.getFlag(), "请选择后缀为JPG、PNG的图片");
            }
            try {
                //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                //此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
                FileUtils.copyInputStreamToFile(myFile.getInputStream(), new File(realPath, saveFileName));
            } catch (IOException e) {
                logger.error("文件[" + originalFilename + "]上传失败,堆栈轨迹如下", e);
                out.print("1文件上传失败，请重试！！");
                out.flush();
            }
        }
        out.print("0" + uploadPath + "\\" + saveFileName);
        out.flush();
//        return realPath+saveFileName;
    }


    private  int successCount;

    public int getSuccessCount() {
        return successCount;
    }
}
